package cn.edu.ecut.se2024.dao;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Many;

import cn.edu.ecut.se2024.model.JSP;
import cn.edu.ecut.se2024.model.Resp;
import cn.edu.ecut.se2024.model.User;
import cn.edu.ecut.se2024.model.UserMenu;

@Mapper
public interface SysDAO {
	@Select("select user_id, user_name, nick_name, password from user where user_name = #{name} and password = #{pswd}")
	User login(@Param("name") String name, @Param("pswd") String pswd);
	
	@Select("select user_id, user_name, nick_name, password from user where user_name = #{name}")
	User findUserByName(@Param("name") String name);	
	
	@Update("UPDATE user SET password = #{newPswd} WHERE user_id = #{userId} and password = #{oldPswd}")
    int changePassword(int userId, String oldPswd, String newPswd);
	
	@Update("UPDATE user SET user_name = #{userName}, nick_name = #{nickName}, password = #{password} WHERE user_id = #{userId}")
    int updateUser(User user);
	
	@Insert("insert into user SET user_name = #{userName}, nick_name = #{nickName}, password = #{password}")
    int insertUser(User user);
	
	@Delete("delete from user where user_id = #{userId}")
	public int deleteUser(int userId);
	
    @Select("SELECT r.resp_id, r.resp_name FROM user_resp ur, resp r "
    		+ "WHERE ur.resp_id = r.resp_id and r.is_valid = 1 and ur.user_id = #{userId}")
    @Results({
        @Result(id = true, property = "respId", column = "resp_id"),
        @Result(property = "respName", column = "resp_name"),
        @Result(property = "jsps", column = "resp_id", many = @Many(select = "getRespJsps"))
    })
    public List<Resp> getUserResps(@Param("userId") int userId);    

	@Select("select j.jsp_code, j.jsp_name, rj.show_in_menu, j.jsp_url "
			+ "from resp_jsp rj, jsp j where rj.jsp_code = j.jsp_code and j.is_valid = 1 and rj.resp_id = #{respId} order by rj.menu_seq")
    @Results({
        @Result(id = true, property = "jspCode", column = "jsp_code"),
        @Result(property = "jspName", column = "jsp_name"),
        @Result(property = "showInMenu", column = "show_in_menu"),
        @Result(property = "jspUrl", column = "jsp_url")
    })
	public List<JSP> getRespJsps(@Param("respId") int respId);
}
